package com.xcf.leetcode;

/**
 * MergeOrderList <br>
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * <p>
 * <p>
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 * @author xiaocf <br>
 * @version 1.0 <br>
 * @date 2020/7/7 9:39 <br>
 */
public class MergeOrderList {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head = new ListNode( );
        ListNode current = head;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                current.next = new ListNode(l2.val);
                l2 = l2.next;
            } else if (l2 == null) {
                current.next = new ListNode(l1.val);
                l1 = l1.next;
            } else if (l1.val < l2.val) {
                current.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                current.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            current = current.next;
        }
        return head.next;
    }

    public static void main(String[] args) {
        ListNode node = build(new int[]{1, 2, 3});
        ListNode node2 = build(new int[]{1, 2, 4});
        MergeOrderList merger = new MergeOrderList( );
        ListNode listNode = merger.mergeTwoLists(node, node2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    private static ListNode build(int[] ints) {
        ListNode head = new ListNode(ints[0]);
        ListNode curr = head;
        for (int i = 1; i < ints.length; i++) {
            curr.next = new ListNode(ints[i]);
            curr = curr.next;
        }
        return head;
    }
}
